import { Form, Row, Col, Input, Button, Table, Spin, Space, Badge, message, Select } from 'antd';
import { Ref, useEffect, useMemo, useRef, useState } from 'react';

import { getSelectExpertsColumns } from '../mconfig';
import '../common/style.less';

import { useDescriptionsType, DescriptionsType } from '@/components/DescriptionsType';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { getLoadMapList, getSelectDataCommon, getTenantID, onCloseModalCommon } from '@/utils';
import { SearchOutlined, RedoOutlined, FilterOutlined } from '@ant-design/icons';
import { ExpertManageService } from '../services/ManageService';
import { addExpertService, getExtractExpertsDataGrid } from '../services/UpdateService';
import { ILoadMapTypeAll } from '@/common';
import { SourceUpdateAPI } from '../common/type';
import { ExtractListDrawer } from './ExtractListDrawer';
import { commonPageSizeOptions } from '@/common/constVariable';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import moment from 'moment';
/**
 * @ExpertsListModal 评标专家弹窗
 * @param onSave 保存事件
 * @param onClose 关闭事件
 * @returns
 */
const ExpertsListModal = ({ onSave, onClose, dataSource, curRes }: SourceUpdateAPI.ExpertsListModalProps) => {
  /** 弹窗Ref */
  const oneModalRef: Ref<IOneModalRef> = useRef(null);

  /** 表单Form */
  const [searchForm] = Form.useForm();

  /** 子组件表单ref  第二步步骤 */
  const extractFormRef = useRef<SourceUpdateAPI.IExtractListFormRef>(null);

  /** 样式 */
  const className = 'expertsList-modalSelect';

  /** 列表与表单渲染状态 */
  const [isShowFrom, setIsShowFrom] = useState<boolean>(true);

  /** Table */
  const [rowList, setRowList] = useState<Record<string, any>[]>([]);

  /** 是否显示 【抽取专家弹窗】 */
  const [isShowExtractModal, setIsShowExtractModal] = useState(false);

  /** 专家库services */
  const { expertRun, expertDataSource, expertLoading, expertTableProps } = ExpertManageService(curRes);

  /** 添加专家到专家库 */
  const { addExpertRun, addExpertLoading } = addExpertService(() => {});

  const extractExpertsCallBack = () => {};

  /**抽取专家接口 */
  const { extractExpertsRun, extractExpertsLoading, extractExpertsData } = getExtractExpertsDataGrid(extractExpertsCallBack);

  /** 数据字典 */
  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.EXPERTS_CARD_TYPE}`,
    `${getTenantID()}${ILoadMapTypeAll.PROFESSIONAL_LIST}`,
    `${getTenantID()}${ILoadMapTypeAll.EXPERTS_INDUSTRY_TYPE}`,
  ];

  /** 字典请求 */
  const { loadMapInfo, mapLoading } = getLoadMapList(loadMdicIds);

  // 证件类型
  const experts_type = getSelectDataCommon(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.EXPERTS_CARD_TYPE}`], 'name', 'id');
  // 职称
  const ZC = getSelectDataCommon(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.PROFESSIONAL_LIST}`], 'name', 'id');
  // 从事专业
  const CSZY = getSelectDataCommon(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.EXPERTS_INDUSTRY_TYPE}`], 'name', 'id');

  const [config, methods] = useDescriptionsType({
    name: 'add-experts',
    labelWidth: 220,
    isShowNumTitle: false,
    schemas: [
      {
        key: 'expert-info',
        title: '专家基本信息',
        fieldChildren: [
          {
            label: '专家姓名',
            field: 'fullName',
            component: 'Input',
            required: true,
            placeholder: '请输入',
          },
          {
            label: '性别',
            field: 'sex',
            component: 'Render',
            // required: true,
            render: () => {
              return (
                <TagSelect
                  formLabel=""
                  formName="sex"
                  // formRequired={true}
                  radioList={[
                    {
                      value: 0,
                      name: '未知',
                    },
                    {
                      value: 1,
                      name: '先生',
                    },
                    {
                      value: 2,
                      name: '女士',
                    },
                  ]}
                  defalultKeys={0}
                />
              );
            },
          },
          {
            label: '所在单位',
            field: 'companyName',
            component: 'Input',
            required: true,
            colSpan: 2,
            placeholder: '请输入',
          },
          {
            label: '职称',
            field: 'rankType',
            component: 'Select',
            required: true,
            fieldNames: { label: 'name', value: 'value' },
            options: ZC,
            placeholder: '请选择',
            message: '请选择职称',
          },
          {
            label: '联系电话',
            field: 'phoneMobile',
            component: 'Input',
            required: true,
            placeholder: '请输入',
          },
          {
            label: '证件类型',
            field: 'cardType',
            component: 'Select',
            options: experts_type,
            fieldNames: { label: 'name', value: 'value' },
            // required: true,
            placeholder: '请选择',
            message: '请选择证件类型',
          },
          {
            label: '证件号码',
            field: 'cardNum',
            component: 'Input',
            // required: true,
            placeholder: '请输入',
          },
          {
            label: '开户行名称',
            field: 'bankName',
            component: 'Input',
            // required: true,
            placeholder: '请输入',
          },
          {
            label: '银行账户',
            field: 'bankNum',
            component: 'Input',
            // required: true,
            placeholder: '请输入',
          },
          {
            label: '从事专业',
            field: 'industryType',
            component: 'Select',
            required: true,
            colSpan: 2,
            fieldNames: { label: 'name', value: 'value' },
            options: CSZY,
            mode: 'multiple',
            maxTagCount: 3,
            placeholder: '请选择',
            message: '请选择从事专业',
          },
          {
            label: '研究方向',
            field: 'graduateMajor',
            component: 'InputTextArea',
            autoSize: { minRows: 3, maxRows: 4 },
            required: true,
            colSpan: 2,
            placeholder: '请输入',
          },
          {
            label: '内外部专家',
            field: 'expertFlag',
            component: 'Render',
            required: true,
            colSpan: 2,
            render: () => {
              return (
                <TagSelect
                  formLabel=""
                  formName="expertFlag"
                  formRequired={true}
                  radioList={[
                    {
                      value: 0,
                      name: '内部专家',
                    },
                    {
                      value: 1,
                      name: '外部专家',
                    },
                  ]}
                  defalultKeys={0}
                />
              );
            },
          },
        ],
      },
    ],
  });

  /** 保存事件 */
  const onModalOk = async () => {
    let returnArr: any = null;
    if (!isShowFrom) {
      const result = await methods?.validateFields();
      let reqObj = {
        ...result,
        industryType: result?.industryType?.join(','),
      };
      addExpertRun(reqObj)?.then((res) => {
        if (res?.msgFlag) {
          message?.success(res?.msg);
          setIsShowFrom(true);
          expertRun({ current: 1, pageSize: 10 });
        }
      });
    } else {
      returnArr = rowList?.forEach((item) => (item.sourceType = 0));
      onSave(rowList, isShowFrom);
      onCloseModalCommon(oneModalRef);
    }
  };

  /** Table选择方法 */
  const onSelectChange = (_: React.Key[], selectedRows: Record<string, any>[]) => {
    setRowList(selectedRows);
  };

  /** 底部按钮 */
  const footerRender = () => {
    return (
      <>
        {curRes?.['/purchaseSourceExpertController/addExpertInfo'] && (
          <Button type={'primary'} onClick={() => setIsShowFrom(!isShowFrom)}>
            {isShowFrom ? '添加' : '选择'}
          </Button>
        )}
        <Button onClick={() => onCloseModalCommon(oneModalRef)}>取消</Button>
        <Button type={'primary'} onClick={onModalOk}>
          确认
        </Button>
      </>
    );
  };

  /** 初始请求 */
  useEffect(() => {
    expertRun({ current: 1, pageSize: 10 });
  }, []);

  /** 抽取专家 */
  const onExtract = () => {
    setIsShowExtractModal(true);
  };

  /** 重置 */
  const onReset = () => {
    searchForm?.resetFields();
    expertRun({ current: 1, pageSize: 10 });
    extractFormRef?.current?.onReload();
  };

  /** 搜索 */
  const onSearch = async () => {
    const formResult = await searchForm?.getFieldsValue();
    expertRun({ current: 1, pageSize: 10, ...formResult, rankType: formResult?.rankType?.join(',') });
  };

  /** 有抽选数据时  调用【抽选专家】 接口*/
  const onSearchExtract = async () => {
    const reqList = extractFormRef?.current?.firstForm?.getFieldValue('extractTable');
    const mapList = reqList?.map((item) => {
      return {
        ...item,
        companyNames: item.companyNames?.join(','),
      };
    });
    let reqObj = {
      mexpertInfoList: mapList,
    };
    extractExpertsRun(reqObj);
  };

  /** 监听抽选专家数据  有则用【抽选专家】 默认返回dataGrid数据*/
  const allExtractData = useMemo(() => {
    if (extractFormRef?.current?.firstForm?.getFieldValue('extractTable')?.length > 0) {
      return extractExpertsData || [];
    } else {
      return expertDataSource;
    }
  }, [extractFormRef, extractExpertsData, expertDataSource]);

  /** 统计抽选专家个数 */
  const badgeData = useMemo(() => {
    let newData = extractFormRef?.current?.firstForm?.getFieldValue('extractTable');
    let extractCount = 0;
    if (newData?.length > 0) {
      newData?.map((item: any) => {
        extractCount += Number(item.count);
      });
      return extractCount;
    }
  }, [extractFormRef?.current?.firstForm?.getFieldValue('extractTable')]);

  /** 表格分页方法改变事件 */
  const handlePaginationChange = (current, pageSize, params) => {
    expertRun({ pageSize, current, ...params, ...searchForm.getFieldsValue() });
  };

  return (
    <>
      <OneModal
        open={true}
        onCancel={onClose}
        centered={true}
        className={className}
        title={!isShowFrom ? '添加专家' : '选择专家'}
        bodyStyle={{ height: '600px', padding: '5px 0px', overflow: 'hidden' }}
        width={document.body.clientWidth * 0.65}
        ref={oneModalRef}
        footer={footerRender()}
        confirmLoading={expertLoading || extractExpertsLoading}
      >
        <Spin spinning={expertLoading || extractExpertsLoading}>
          {isShowFrom && (
            <div className="source-selectExpertModal">
              <Form form={searchForm}>
                <Row gutter={[8, 0]} style={{ padding: '10px 1rem' }}>
                  <Col span={6}>
                    <Form.Item name="fullName">
                      <Input placeholder="姓名" allowClear />
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Form.Item name="companyName">
                      <Input placeholder="所在单位" allowClear />
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    {/* <Form.Item name="cardNum">
                      <Input placeholder="身份证号码" allowClear />
                    </Form.Item> */}
                    <Form.Item name="rankType">
                      <Select
                        placeholder="职称"
                        fieldNames={{ label: 'name', value: 'value' }}
                        options={ZC}
                        mode={'multiple'}
                        maxTagCount={1}
                        filterOption={(input, option: any) => {
                          return (option?.children ?? '').toLowerCase().includes(input.toLowerCase());
                        }}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={6} style={{ textAlign: 'right' }}>
                    <Space>
                      {extractFormRef?.current?.firstForm?.getFieldValue('extractTable') &&
                      extractFormRef?.current?.firstForm?.getFieldValue('extractTable')?.length > 0 ? (
                        <Button type="primary" icon={<SearchOutlined />} onClick={onSearchExtract}>
                          查询
                        </Button>
                      ) : (
                        <Button type="primary" icon={<SearchOutlined />} onClick={onSearch}>
                          查询
                        </Button>
                      )}

                      <Button icon={<RedoOutlined />} onClick={onReset}>
                        重置
                      </Button>
                      <Badge count={badgeData}>
                        <Button icon={<FilterOutlined />} onClick={onExtract}>
                          更多
                        </Button>
                      </Badge>
                    </Space>
                  </Col>
                </Row>
              </Form>
              <div className={'list-table'} style={{ position: 'relative', flex: 'auto', overflow: 'hidden' }}>
                <Table
                  bordered
                  size="small"
                  columns={getSelectExpertsColumns()}
                  dataSource={allExtractData}
                  loading={false}
                  scroll={{ x: 'true', y: 'true' }}
                  rowKey={(record: any) => record?.expertID}
                  rowSelection={{
                    type: 'checkbox',
                    onChange: onSelectChange,
                    getCheckboxProps: (record) => {
                      return {
                        disabled: Boolean(dataSource?.find((item) => item?.expertID === record?.expertID)),
                      };
                    },
                  }}
                  pagination={
                    {
                      // ...expertTableProps,
                      pageSize: expertTableProps?.pageSize,
                      current: expertTableProps?.current,
                      total: expertTableProps?.total,
                      showQuickJumper: true,
                      showSizeChanger: true,
                      pageSizeOptions: commonPageSizeOptions,
                      onChange: handlePaginationChange,
                    } as any
                  }
                ></Table>

                <ExtractListDrawer
                  visible={isShowExtractModal}
                  expertDataSource={expertDataSource}
                  onClose={() => setIsShowExtractModal(false)}
                  ref={extractFormRef}
                />
              </div>
            </div>
          )}
          {!isShowFrom && (
            <div style={{ margin: '10px 1rem' }}>
              <Spin spinning={addExpertLoading || mapLoading}>
                <DescriptionsType config={config} />
              </Spin>
            </div>
          )}
        </Spin>
      </OneModal>
    </>
  );
};

export default ExpertsListModal;
